From 8fe34b2650a1be83cb3e99085e2f300caab54063 Mon Sep 17 00:00:00 2001 From: NW/RL Date: Sat, 13 Apr 2024 22:26:07 -0500 Subject: Make documentation look significantly better --- steamrelationships/sr.py | 90 ++++++++++++++++++++++++------------------------ 1 file changed, 45 insertions(+), 45 deletions(-) (limited to 'steamrelationships') diff --git a/steamrelationships/sr.py b/steamrelationships/sr.py index 28b6b16..63122b4 100644 --- a/steamrelationships/sr.py +++ b/steamrelationships/sr.py @@ -8,14 +8,14 @@ CONST = _Const() class SteamRelationships: """A class that handles the querring of Steam's web api to request a user's friends list""" - + session: object = requests.Session() # Session object so repeated querries to steam's api use the same TCP connection scanlist: dict = {} # To be populated by scan functions def __init__(self, webapikey: str, timeout: int = 30, timeout_retries: int = 5, reqdelay: float = 0.5, delayrand: int = 25, reqsafetybuffer: float = 0.9, reqjson: str = "requests.json") -> None: """ (str) webapikey - A Steam "web api key" for grabbing friends lists (get one at https://steamcommunity.com/dev/apikey) - + (int) timeout (Default: 30) - The time in seconds to wait for a response from Steam before timing out (int) timeout_retries (Default: 5) - The number of times to retry a scan after a timeout (float) reqdelay (Default: 0.5) - The base amount of seconds to wait after each scan (to lessen the load on Steam's servers) @@ -40,14 +40,14 @@ class SteamRelationships: def __str__(self) -> str: return f"Vals:\n\twebapikey: {len(self.webapikey) > 0} (Actual value ommitted for security)\n\n\tTimeout: {self.timeout}\n\tTimeout Retries: {self.timeout_retries}\n\tRequest Delay: {self.reqdelay}\n\tRequest Delay Randomness Factor: +/- {self.delayrand}%\n\tRequest Safety Buffer: {self.reqsafetybuffer} ({self.reqsafetybuffer * CONST.STEAMAPI_MAXREQ} out of {CONST.STEAMAPI_MAXREQ} max requests)\n\tRequests Log Filepath: \"{self.reqjson}\"\n\n\tMost Recent Scan: {self.scanlist}" - def _readjsonfile(self, filepath: str = "") -> dict: + def __readjsonfile(self, filepath: str = "") -> dict: """ - _readjsonfile(self, filepath: str = "") -> dict: Read the specified json file for previous requests + __readjsonfile(self, filepath: str = "") -> dict: Read the specified json file for previous requests filepath: Path to json file - + dict (return): The contents of the json file. Empty on error - _readjsonfile will create an "empty" json file if the specified file at the filepath doesn't exist + __readjsonfile will create an "empty" json file if the specified file at the filepath doesn't exist """ if not filepath: filepath = self.reqjson @@ -63,31 +63,31 @@ class SteamRelationships: # If the file does not exist, create one and slap an empty list in it except FileNotFoundError: - print(f"[_readjsonfile] File {filepath} does not exist. Generating empty json file...") + print(f"[__readjsonfile] File {filepath} does not exist. Generating empty json file...") try: with open(filepath, "w+") as newfile: json.dump({time.time_ns(): [0, []]}, newfile, indent=CONST.JSON_INDENT) newfile.close() - return self._readjsonfile(filepath) + return self.__readjsonfile(filepath) except Exception as e: - print(f"[_readjsonfile] Couldn't create new file ({e})") + print(f"[__readjsonfile] Couldn't create new file ({e})") return {} except Exception as e: - print(f"[_readjsonfile] Other unknown error occured ({e})") + print(f"[__readjsonfile] Other unknown error occured ({e})") return {} return final - def _checkrequests(self, filename: str = "") -> int: + def __checkrequests(self, filename: str = "") -> int: """ - _checkrequests(self, filename: str = "") -> int: Check the requests log to make sure Steam's request limit hasn't been passed + __checkrequests(self, filename: str = "") -> int: Check the requests log to make sure Steam's request limit hasn't been passed filename: filepath to requests log int (return): The number of requests in the last 24 hours. -1 on error, 0 on too many requests, and >1 if a valid number of requests - _checkrequests will create a file at filepath if it doesn't exist. It will also never go over 100,000 requests, regardless of what reqsafetybuffer is + __checkrequests will create a file at filepath if it doesn't exist. It will also never go over 100,000 requests, regardless of what reqsafetybuffer is """ if not filename: filename = self.reqjson @@ -95,10 +95,10 @@ class SteamRelationships: # Get the contents of the specified file jsoncontents: dict = {} try: - jsoncontents = self._readjsonfile(filename) + jsoncontents = self.__readjsonfile(filename) except Exception as e: - print(f"[_checkrequests] Could not get the contents of file \"{filename}\" ({e})") + print(f"[__checkrequests] Could not get the contents of file \"{filename}\" ({e})") return -1 # Check the current date. If over 1 day since last entry, add a new entry. Otherwise, edit the current day's entry [note, 1 day in nanoseconds = (8.64 * (10 ** 13)) ] @@ -114,7 +114,7 @@ class SteamRelationships: jsoncontents[list(jsoncontents.keys())[-1]][1].append(checktime) else: - print(f"[_checkrequests] Daily request limit reached ({currentreqs}/{CONST.STEAMAPI_MAXREQ * self.reqsafetybuffer}). Please try again tomorrow, or increase \"reqsafetybuffer\" (currently: {self.reqsafetybuffer})") + print(f"[__checkrequests] Daily request limit reached ({currentreqs}/{CONST.STEAMAPI_MAXREQ * self.reqsafetybuffer}). Please try again tomorrow, or increase \"reqsafetybuffer\" (currently: {self.reqsafetybuffer})") return 0 # Update the json file @@ -124,28 +124,28 @@ class SteamRelationships: jsonfile.close() except Exception as e: - print(f"[_checkrequests] Could not update json file ({e})") + print(f"[__checkrequests] Could not update json file ({e})") return -1 return jsoncontents[list(jsoncontents.keys())[-1]][0] - def _getFriendsList(self, steamid64: str, _retries: int = 0) -> dict: + def __getFriendsList(self, steamid64: str, _retries: int = 0) -> dict: """ - _getFriendsList(self, steamid64: str, _retries: int = 0) -> dict: Send a request to the Steam Web API to get a user's friends list + __getFriendsList(self, steamid64: str, _retries: int = 0) -> dict: Send a request to the Steam Web API to get a user's friends list steamid64: A Steam User's id, in the steamid64 format _retries: An internal value used to limit the number of retries after a timeout. Increments by one automatically on every timeout - + dict (return): The json representation of Steam's response. Empty on error """ if not steamid64: - print("[_getFriendsList] No steamid64 given") + print("[__getFriendsList] No steamid64 given") return {} # Make sure we haven't gone over steam's daily max - if self._checkrequests() == 0: - print("[_getFriendsList] Max requests reached, refusing to contact steam") + if self.__checkrequests() == 0: + print("[__getFriendsList] Max requests reached, refusing to contact steam") return {} url: str = "https://api.steampowered.com/ISteamUser/GetFriendList/v0001/" @@ -157,24 +157,24 @@ class SteamRelationships: result = self.session.get(url, params=options, timeout=self.timeout) except requests.exceptions.Timeout: - print(f"[_getFriendsList] Request timed out (No response for {self.timeout} seconds)") + print(f"[__getFriendsList] Request timed out (No response for {self.timeout} seconds)") if _retries <= self.timeout_retries: - print(f"[_getFriendsList] Retrying request... (Attempt {_retries}/{self.timeout_retries})") - return self._getFriendsList(steamid64, _retries + 1) + print(f"[__getFriendsList] Retrying request... (Attempt {_retries}/{self.timeout_retries})") + return self.__getFriendsList(steamid64, _retries + 1) - print("[_getFriendsList] Retry limit reached") + print("[__getFriendsList] Retry limit reached") return {} except Exception as e: - print(f"[_getFriendsList] Other error in contacting steam ({e})") + print(f"[__getFriendsList] Other error in contacting steam ({e})") return {} # Error out on request error if result.status_code != requests.codes.ok: - print(f"[_getFriendsList] Got bad status code (Requested id: {steamid64}, status: {result.status_code})", end="") + print(f"[__getFriendsList] Got bad status code (Requested id: {steamid64}, status: {result.status_code})", end="") if result.status_code == 401: # Steam returns a 401 on profiles with private friends lists print(f". It is likely that the requested id has a private profile / private friends list", end="") - + print("\n", end="") return {} @@ -184,25 +184,25 @@ class SteamRelationships: resultjson = result.json() except requests.exceptions.JSONDecodeError: - print("[_getFriendsList] Could not decode json response for some reason") + print("[__getFriendsList] Could not decode json response for some reason") return {} except Exception as e: - print(f"[_getFriendsList] Unknown error in getting json response ({e})") + print(f"[__getFriendsList] Unknown error in getting json response ({e})") return {} return resultjson - def _parseFriendsList(self, friendsdict: dict) -> list: + def __parseFriendsList(self, friendsdict: dict) -> list: """ - _parseFriendsList(self, friendsdict: dict) -> list: Parse a response from Steam and extract a user's friend's Steam IDs - friendsdict: The return value of _getFriendsList + __parseFriendsList(self, friendsdict: dict) -> list: Parse a response from Steam and extract a user's friend's Steam IDs + friendsdict: The return value of __getFriendsList list (return): The steamid64's of a user's friends. Empty on error """ if not friendsdict: - print("[_parseFriendsList] Empty friends dict given") + print("[__parseFriendsList] Empty friends dict given") return [] @@ -212,7 +212,7 @@ class SteamRelationships: people.append(f'{friend["steamid"]}') except Exception as e: - print("[_parseFriendsList] Error parsing friendsdict ({e})") + print("[__parseFriendsList] Error parsing friendsdict ({e})") people.clear() return people @@ -229,7 +229,7 @@ class SteamRelationships: (dict) {steamid64: [friendID1, friendID2, ...]} - A dict with a single key, that of the scanned user, which maps to a list of the users's friends ''' - self.scanlist = {steamid64: self._parseFriendsList(self._getFriendsList(steamid64))} + self.scanlist = {steamid64: self.__parseFriendsList(self.__getFriendsList(steamid64))} return self.scanlist def recursivescan(self, steamid64: str, recurselevel: int = 2) -> dict: @@ -244,12 +244,12 @@ class SteamRelationships: RETURN VALUES: (dict) EMPTY - Some catastrophic error has occured and no scan could be started (dict) { - steamid64: - [friend1id, friend2id, friend3id, ...], - friend1id: - [other_friend, other_friend, ...], - friend2id: - [other_friend, other_friend, ...], + steamid64: + [friend1id, friend2id, friend3id, ...], + friend1id: + [other_friend, other_friend, ...], + friend2id: + [other_friend, other_friend, ...], friend3id: [other_friend, other_friend, ...], ... @@ -276,7 +276,7 @@ class SteamRelationships: sleepytime: float = abs(random.randrange(100 - self.delayrand, 100 + self.delayrand) / 100 * self.reqdelay) time.sleep(sleepytime) - + testlist.update(tempdict) tempdict.clear() -- cgit v1.2.3