I've made a nice little Python program using the requests
module using the Trade.tf Developer API and the Steam WebAPI allowing the user to look up the price of Team Fortress 2 items through Trade.tf's spreadsheet.
For those of you that may not know, Team Fortress 2 is a free-to-play team-based shooter game which also features quite a large e-economy for in-game items. Sites such as Backpack.tf and Trade.tf exist to show pricing of items in terms of various currency-like items such as refined metal (a crafting ingredient in-game) and keys (used to open supply crates which can unlock various items within them).
I know there's definitely something that can be improved in this program, but I'm not fully sure on how I can accomplish this. Feel free to make any suggestions for it.
import json
import requests
import time
with open('keys.json', 'r') as f:
keys = json.load(f)
schema = requests.get('http://api.steampowered.com/IEconItems_440/GetSchema/v0001/?key=' + keys['steam'])
spreadsheet = requests.get('http://www.trade.tf/api/spreadsheet.json?key=' + keys['tradetf'])
qualities = {"uncraft" : -1,
"genuine" : 1,
"vintage" : 3,
"unique" : 6,
"strange" : 11,
"haunted" : 13} # all qualities currently tracked by Trade.TF
def get_item_defindex_from_name(name):
for items in schema.json()["result"]["items"]:
if items["name"] == name:
defindex = items["defindex"]
if defindex:
return defindex
else:
print("Invalid item.")
def get_quality_id_from_name(name):
return qualities[name]
def get_price_unit(unit):
return {
"r": " refined",
"k": " keys",
"b": " buds"}.get(unit, " ")
def get_tradetf_price(item, quality):
price = spreadsheet.json()["items"][str(item)][str(quality)]["regular"]["hi"]
unit = get_price_unit(spreadsheet.json()["items"][str(item)][str(quality)]["regular"]["unit"])
return str(price) + unit
def get_input(dialog, validation, error_message):
while True:
answer = input(dialog)
if validation(answer):
return answer
else:
print(error_message)
def main():
try:
while True:
try:
item_name = str(input("Enter item name: "))
item_ = get_item_defindex_from_name(item_name)
break
except UnboundLocalError:
print("Invalid item.")
quality = get_input(
"Enter item quality: ",
lambda quality: quality.lower() in qualities,
"Quality not tracked by Trade.tf."
)
quality_ = get_quality_id_from_name(quality.lower())
print("\n", quality, item_name, "price: ", get_tradetf_price(item_, quality_))
except KeyError:
print("Item not currently tracked by Trade.tf.")
if __name__ == "__main__":
main()
print("Shutting down...")
time.sleep(3)
"result"
and"items"
. That way, your code is easier to read. \$\endgroup\$