Skip to content

Commit

Permalink
Various code format changes inline with Flake8 standards.
Browse files Browse the repository at this point in the history
  • Loading branch information
Jack Brown committed Nov 11, 2023
1 parent 31638fd commit 0f8ae16
Show file tree
Hide file tree
Showing 6 changed files with 64 additions and 55 deletions.
59 changes: 30 additions & 29 deletions OSRSBytes/Hiscores.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,6 @@
# Generic/Built-in Imports
import http.client
import math
import os
import time

from OSRSBytes.Utilities import Utilities

# META Data
__copyright__ = 'Copyright 2023, CFDeadlines'
Expand All @@ -31,36 +27,45 @@
__status__ = 'Open'
__test__ = "this is a test again"


################
# Exceptions #
################
class DoNotRunDirectly(Exception):
pass


class SkillError(Exception):
pass


class ClueError(Exception):
pass


class HiscoresError(Exception):
pass


class LMSArenaError(Exception):
pass


class BossError(Exception):
pass


class BountyError(Exception):
pass


############################
# Do not run if __main__ #
############################
if __name__ == "__main__":
raise DoNotRunDirectly("This library is not meant to be called as __main__, import it instead.")


############################
# START: Hiscores Object #
############################
Expand Down Expand Up @@ -120,19 +125,19 @@ def __getHTTPResponse(self):
"""
conn = http.client.HTTPSConnection('secure.runescape.com')
if self.accountType == 'N':
conn.request("GET", "/m=hiscore_oldschool/index_lite.ws?player={}".format(self.username.replace(' ','%20')))
conn.request("GET", "/m=hiscore_oldschool/index_lite.ws?player={}".format(self.username.replace(' ', '%20')))
self.response = conn.getresponse()
self.status = self.response.status
elif self.accountType == 'IM':
conn.request("GET", "/m=hiscore_oldschool_ironman/index_lite.ws?player={}".format(self.username.replace(' ','%20')))
conn.request("GET", "/m=hiscore_oldschool_ironman/index_lite.ws?player={}".format(self.username.replace(' ', '%20')))
self.response = conn.getresponse()
self.status = self.response.status
elif self.accountType == "UIM":
conn.request("GET", "/m=hiscore_oldschool_ultimate/index_lite.ws?player={}".format(self.username.replace(' ','%20')))
conn.request("GET", "/m=hiscore_oldschool_ultimate/index_lite.ws?player={}".format(self.username.replace(' ', '%20')))
self.response = conn.getresponse()
self.status = self.response.status
elif self.accountType == "HIM":
conn.request("GET", "/m=hiscore_oldschool_hardcore_ironman/index_lite.ws?player={}".format(self.username.replace(' ','%20')))
conn.request("GET", "/m=hiscore_oldschool_hardcore_ironman/index_lite.ws?player={}".format(self.username.replace(' ', '%20')))
self.response = conn.getresponse()
self.status = self.response.status
self.__processResponse()
Expand Down Expand Up @@ -168,19 +173,19 @@ def __parseSkills(self):
subset = {}
# Totals
info = {}

# Split data into lists
for value in self.data.split(" "):
total_info = value.split(",")

# assign into dictionary
info['rank'] = total_info[0]
info['level'] = total_info[1]
info['experience'] = total_info[2]
break

subset['total'] = info

self.__skills = [
'attack',
'defense',
Expand Down Expand Up @@ -217,15 +222,15 @@ def __parseSkills(self):

# calculate xp to next level
level = info['level'] + 1

# If 200M XP, set next level and exp to next to 0
if (int(info['experience']) == 200000000):
info['next_level_exp'] = 0
info['exp_to_next_level'] = 0
else:
info['next_level_exp'] = math.floor(sum((math.floor(level + 300 * (2 ** (level / 7.0))) for level in range(1, level)))/4)
info['exp_to_next_level'] = int(info['next_level_exp'] - info['experience'])

subset[skill] = info
self.__parsed_data.remove(item)
break
Expand Down Expand Up @@ -253,7 +258,6 @@ def __parseBountyHunter(self):

self.bounties[self.username] = subset


def __parseClues(self):
subset = {}
self.__clue_tiers = [
Expand Down Expand Up @@ -321,10 +325,9 @@ def __getBossList(self):
bosses = []
for boss in boss_list_unsanitized:
if boss:
bosses.append(boss.split("activity-link ",1)[1].split("\">",1)[0])
bosses.append(boss.split("activity-link ",1)[1].split("\">", 1)[0])
return bosses


def __parseBosses(self):
subset = {}

Expand All @@ -342,7 +345,6 @@ def __parseBosses(self):

self.bosses[self.username] = subset


def __parseData(self):
self.stats = {}
self.bounties = {}
Expand All @@ -353,20 +355,19 @@ def __parseData(self):

# Prep data for parsing
self.__parsed_data = self.data.split("\n")
self.__parsed_data.pop(0) # remove totals section
self.__parsed_data.pop(0) # Remove totals section

self.__parseSkills()

# Skip over unused values for most people
self.__parsed_data.pop(0) # Skip over "unknown" (open issue if you know it)
self.__parsed_data.pop(0) # Needed to add another of these for some reason?
self.__parsed_data.pop(0) # Skip over "unknown" (open issue if you know it)
self.__parsed_data.pop(0) # Needed to add another of these for some reason?

self.__parseBountyHunter()
self.__parseClues()
self.__parseLMS()
self.__parseBosses()


def skill(self, skill, stype: str = 'level'):
"""skill() method
Expand All @@ -387,7 +388,7 @@ def skill(self, skill, stype: str = 'level'):
"""
try:
if stype.lower() not in ['rank','level','experience','exp_to_next_level']:
if stype.lower() not in ['rank','level','experience', 'exp_to_next_level']:
raise SkillError("stype must be 'rank','level', or 'experience'")
else:
return self.stats[self.username][skill.lower()][stype.lower()]
Expand All @@ -410,7 +411,7 @@ def clue(self, clue_tier, clue_type: str = 'score'):
self.clues[username][clue_tier][clue_type] (int)
"""
try:
if clue_type.lower() not in ["rank","score"]:
if clue_type.lower() not in ["rank", "score"]:
raise ClueError("clue_type must be 'rank' or 'score'")
else:
return self.clues[self.username][clue_tier.lower()][clue_type.lower()]
Expand All @@ -434,7 +435,7 @@ def bounty(self, bounty, bounty_type: str = 'score'):
self.bounties[username][bounty_tier][bounty_type] (int)
"""
try:
if bounty_type.lower() not in ["rank","score"]:
if bounty_type.lower() not in ["rank", "score"]:
raise BountyError("bounty_type must be 'rank' or 'score'")
else:
return self.bounties[self.username][bounty.lower()][bounty_type.lower()]
Expand All @@ -443,21 +444,21 @@ def bounty(self, bounty, bounty_type: str = 'score'):

def lms_arena_sw(self, activity_type, info_type: str = 'score'):
try:
if info_type.lower() not in ["rank","score"]:
if info_type.lower() not in ["rank", "score"]:
raise LMSArenaError("info_type must be 'rank' or 'score'")
else:
return self.lms_arenas_sw[self.username][activity_type.lower()][info_type.lower()]
except KeyError as KE:
raise LMSArenaError("ERROR: activity_type does not exist".format(KE))
raise LMSArenaError("ERROR: Activity {} does not exist".format(KE))

def boss(self, boss_name, info_type: str = 'score'):
try:
if info_type.lower() not in ["rank","score"]:
if info_type.lower() not in ["rank", "score"]:
raise BossError("info_type must be 'rank' or 'score'")
else:
return self.bosses[self.username][boss_name.lower()][info_type.lower()]
except KeyError as KE:
raise BossError("ERROR: boss_name does not exist")
raise BossError("ERROR: Boss {} does not exist".format(KE))

def error(self):
HiscoresError("Error occurred: {}".format(self.errorMsg))
Expand Down
34 changes: 19 additions & 15 deletions OSRSBytes/Items.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
__email__ = 'cookm0803@gmail.com'
__status__ = 'Open'


################
# Exceptions #
################
Expand All @@ -38,6 +39,7 @@ class DoNotRunDirectly(Exception):
"""
pass


class ItemNotValid(Exception):
"""ItemNotValid Exception
Expand All @@ -46,6 +48,7 @@ class ItemNotValid(Exception):
"""
pass


class APIDown(Exception):
"""APIDown Exception
Expand All @@ -54,12 +57,14 @@ class APIDown(Exception):
"""
pass


############################
# Do not run if __main__ #
############################
if __name__ == "__main__":
raise DoNotRunDirectly("This library is not meant to be called as __main__, import it instead.")


############################
# START: Items Object #
############################
Expand All @@ -78,15 +83,15 @@ class Items(object):
None
"""

def __init__(self, application_name = None, application_contact = None):
def __init__(self, application_name=None, application_contact=None):
self.__application_name = application_name if application_name else "OSRSBytes"
self.__application_contact = application_contact if application_contact else "info@osrsbytes.com"

prices, volumes, mappings = self.__getHTTPRequest()
self.itemname = self.__rectifyWikiResponse(prices, volumes, mappings) # Why did I name you this way?
self.itemname = self.__rectifyWikiResponse(prices, volumes, mappings) # Why did I name you this way?
self.item_dict = self.itemname
if not (self.item_dict):
raise APIDown(f'The API appears to be down, please try the other')
raise APIDown('The API appears to be down, please try the other.')

def __getHTTPRequest(self):
"""getHTTPRequest
Expand All @@ -105,10 +110,9 @@ def __getHTTPRequest(self):
url_prices = 'https://prices.runescape.wiki/api/v1/osrs/latest'
url_volumes = 'https://prices.runescape.wiki/api/v1/osrs/volumes'
headers = {
"User-Agent" : "{} - {}".format(self.__application_name, self.__application_contact)
"User-Agent": "{} - {}".format(self.__application_name, self.__application_contact)
}


req = urllib.request.Request(url_mappings, headers=headers)
f = urllib.request.urlopen(req)
mappings = json.load(f)
Expand Down Expand Up @@ -141,7 +145,7 @@ def __rectifyWikiResponse(self, prices, volumes, mappings):
rect = {}
try:
for item in mappings:
item['name'] = item['name'].lower() # Normalize itemnames
item['name'] = item['name'].lower() # Normalize itemnames
rect[item['name']] = {}
rect[item['name']]['name'] = item['name']
rect[item['name']]['id'] = item['id']
Expand Down Expand Up @@ -194,7 +198,7 @@ def getItem(self, itemNameOrID: str):
return self.item_dict[self.__normalize_input(str(itemNameOrID).lower())]
except KeyError:
raise ItemNotValid("{} is not a valid item and was not found.".format(itemNameOrID))

def getName(self, itemNameOrID: str):
"""getName Method
Expand Down Expand Up @@ -225,7 +229,7 @@ def getSellAverage(self, itemNameOrID: str):
"""getSellAverage Method
The getSellAverage method, when supplied an Item Name or Item ID, returns an integer value containing
the Item's current in-game sell value.
the Item's current in-game sell value.
"""
return self.item_dict[self.__normalize_input(str(itemNameOrID).lower())]['sell_average']

Expand All @@ -242,9 +246,9 @@ def getSellQuantity(self, itemNameOrID: str):
The getSellQuantity method, when supplied an Item Name or Item ID, returns an integer value containing
the Item's current number of in-game sell orders.
"""
"""
return self.item_dict[self.__normalize_input(str(itemNameOrID).lower())]['sell_quantity']

def getBuyLimit(self, itemNameOrID: str):
"""getBuyLimit Method
Expand Down Expand Up @@ -276,7 +280,7 @@ def getHighAlchValue(self, itemNameOrID: str):
"""getHighAlchValue Method
The getHighAlchValue method, when supplied an Item Name or Item ID, returns an integer value containing
the coin return value of casting High Alchemy on the in-game item.
the coin return value of casting High Alchemy on the in-game item.
"""
return math.ceil(self.item_dict[self.__normalize_input(str(itemNameOrID).lower())]['sp']*.60)

Expand All @@ -287,18 +291,18 @@ def isMembers(self, itemNameOrID: str):
on whether the supplied item is Members Only or not.
"""
return bool(self.item_dict[self.__normalize_input(str(itemNameOrID).lower())]['members'])

def update(self):
"""update Method
The update method updates the item information in the object that it is called from and
prevents the need to reinitialize/recreate the Items object.
"""
prices, volumes, mappings = self.__getHTTPRequest()
self.itemname = self.__rectifyWikiResponse(prices, volumes, mappings) # Why did I name you this way?
self.itemname = self.__rectifyWikiResponse(prices, volumes, mappings) # Why did I name you this way?
self.item_dict = self.itemname
if not (self.item_dict):
raise APIDown(f'The API appears to be down, please try the other')
raise APIDown('The API appears to be down, please try the other.')
##########################
# END: Items Object #
##########################
1 change: 1 addition & 0 deletions OSRSBytes/Utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
__email__ = 'cookm0803@gmail.com'
__status__ = 'Open'


class Utilities(object):
def __init__(self):
self.getLocation()
Expand Down
3 changes: 2 additions & 1 deletion OSRSBytes/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,16 @@
__email__ = 'cookm0803@gmail.com'
__status__ = 'Open'


################
# Exceptions #
################
class DoNotRunDirectly(Exception):
pass


############################
# Do not run if __main__ #
############################
if __name__ == "__main__":
raise DoNotRunDirectly("This library is not meant to be called as __main__, import it instead.")

Loading

0 comments on commit 0f8ae16

Please sign in to comment.