Skip to content

Instantly share code, notes, and snippets.

@MikeRixWolfe
Last active February 29, 2024 22:22
Show Gist options
  • Save MikeRixWolfe/9a8d2e86fbf7dab46fe7 to your computer and use it in GitHub Desktop.
Save MikeRixWolfe/9a8d2e86fbf7dab46fe7 to your computer and use it in GitHub Desktop.
Steam Sales Checker (via Big Picture data feeds)
#!/usr/bin/env python
import json
import os
import requests
import time
debug = False
debug_path = 'debug'
def log_sales_data(sales, filename):
# Create dr to log sales for debug purposes
if not os.path.exists(debug_path):
os.makedirs(debug_path)
# Log specified data
with open("{}/{}-{}.json".format(debug_path,
time.strftime('%Y%m%d%H%M', time.localtime()),
filename), "w+") as f:
json.dump(sales, f, sort_keys=True, indent=2)
def get_featured():
sales_url = "http://store.steampowered.com/api/featured/?l=english"
try:
sales = requests.get(sales_url).json()
except:
sales = {}
if debug:
log_sales_data(sales, "featured")
return sales
def get_featuredcategories():
sales_url = "http://store.steampowered.com/api/featuredcategories/?l=english"
try:
sales = requests.get(sales_url).json()
except:
sales = {}
if debug:
log_sales_data(sales, "featuredcategories")
return sales
def get_sales():
apps_url = "http://store.steampowered.com/api/appdetails/?appids="
# Unusable categories
skips = ["coming_soon", "genres", "trailerslideshow", "status"]
# Fetch data
data = get_featuredcategories()
flash_data = get_featured()
# Break if either return empty - might be unnecessary
if not data or not flash_data:
return {}
# Aggregate data
fetchtime = int(time.time())
data["flash"] = {}
data["flash"]["name"] = "Flash Sales"
data["flash"]["items"] = []
data["featured"] = {}
data["featured"]["name"] = "Featured Sales"
data["featured"]["items"] = []
for item in flash_data["large_capsules"]:
if "discount_expiration" not in item.keys():
item["discount_expiration"] = 9999999999
if item["discount_expiration"] - fetchtime <= 43200:
data["flash"]["items"].append(item)
else:
data["featured"]["items"].append(item)
# Mask Data
data = {k: v for k, v in data.items() if isinstance(v, dict)
and k not in skips}
if debug:
log_sales_data(data, "data")
# Format data
sales = {}
for category in data:
if "items" not in data[category].keys():
data[category]["items"] = []
for item in data[category]["items"]:
# Prepare item data
try:
# Bundles
if set(["id", "url"]).issubset(set(item.keys())):
if not item["final_price"] and not item["discounted"]:
item["final_price"] = web.try_googl(item["url"])
item["discounted"] = True
else:
# Midweek Madness, Weekend Deals, etc
if "url" in item.keys() and "id" not in item.keys():
data[category]["name"] = item["name"] or data[category]["name"]
item["id"] = str(item["url"])[34:-1]
appdata = requests.get("{}{}".format(apps_url,
item["id"])).json()[str(item["id"])]["data"]
item["name"] = appdata["name"]
if "Free to Play" in appdata["genres"]:
item["final_price"] = 'Free to Play'
item["discount_percent"] = '100'
else:
item["final_price"] = appdata[
"price_overview"]["final"]
item["discount_percent"] = appdata[
"price_overview"]["discount_percent"]
item["discounted"] = True if int(item["discount_percent"]) > 0 \
else False
except:
# Unusuable Catagory e.g. Banner Announcments
if debug:
print category, item
continue
# Add appropriate item data to sales
if item["discounted"]:
item["name"] = item["name"].replace(" Advertising App", "")
item = {k: u"{}".format(v) for k, v in item.items() if k in
["name", "final_price", "discount_percent"]}
if data[category]["name"] not in sales.keys():
sales[data[category]["name"]] = []
sales[data[category]["name"]].append(item)
# Filter and sort items
sales = {category: sorted([item for item in items if item["name"] != "Uninitialized"],
key=lambda x: x["name"]) for category, items in sales.items()}
if debug:
log_sales_data(sales, "sales")
# Return usable data
return sales
def format_sale_item(item):
if not str(item["final_price"]).isdigit():
return u"{}: {}".format(item["name"],
item["final_price"])
else:
return u"{}: ${}.{}({}% off)".format(item["name"],
item["final_price"][:-2],
item["final_price"][-2:],
item["discount_percent"])
if __name__ == "__main__":
import codecs
import sys
from collections import OrderedDict
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
sys.stderr = codecs.getwriter('utf8')(sys.stderr)
# Get sales
sales = get_sales()
# If sales not returned
if not sales:
print("Steam Store API error, no data returned. "
"Turn on debug and check logs for more info.")
# Output appropriate data
for category in OrderedDict(sorted(sales.items())):
items = [format_sale_item(item) for item in sales[category]]
print(u"{}:\n\t{}".format(category, u"\n\t".join(items)))
@ItsFranklinMyDudes
Copy link

it doesnt work, idk how python works but it doesnt work at all, there was a error on line 124 for print but now it just gives me this

object address  : 000001A15B506EC0
object refcount : 2
object type     : 00007FF9F63DDA90
object type name: TypeError
object repr     : TypeError('write() argument must be str, not bytes')
lost sys.stderr

also web isnt defined

@MikeRixWolfe
Copy link
Author

MikeRixWolfe commented Feb 29, 2024

@ItsFranklinMyDudes run with python2.7 and it works. This was written 8 years ago, updating it for python3 is left as an exercise for the interested party.

@ItsFranklinMyDudes
Copy link

@ItsFranklinMyDudes run with python2.7 and it works. This was written 8 years ago, updating it for python3 is left as an exercise for the interested party.

fuck it’s messing info, alr ty i’ll try it again

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment