Files
Valve_research/prices.py
T
2026-11-19 14:06:28 +01:00

192 lines
6.3 KiB
Python

#!/usr/bin/env python3
"""
Scan a folder for files named "<steam_app_id>.csv", look each ID up on Steam,
and report current price/discount plus price history.
Usage:
python steam_prices.py /path/to/folder
ITAD_KEY=yourkey python steam_prices.py /path/to/folder
"""
import csv
import os
import re
import sys
import time
from pathlib import Path
import requests
COUNTRY = "dk" # Steam region / currency (dk = DKK)
ITAD_KEY = os.environ.get("76f40eccf89a67fc2fd656a273e060e3000d5050") # optional, enables full history
STEAM_SHOP_ID_ITAD = 61 # Steam's shop id on IsThereAnyDeal
DELAY = 1.5 # seconds between apps (Steam rate limits)
session = requests.Session()
session.headers["User-Agent"] = "steam-price-checker/1.0"
def find_ids(folder: Path):
ids = []
for f in folder.iterdir():
m = re.fullmatch(r"(\d+)\.csv", f.name, re.IGNORECASE)
if m:
ids.append(int(m.group(1)))
return sorted(ids)
def steam_current(app_id):
"""Current price + discount from the Steam Store API."""
r = session.get(
"https://store.steampowered.com/api/appdetails",
params={"appids": app_id, "cc": COUNTRY, "filters": "basic,price_overview"},
timeout=15,
)
r.raise_for_status()
entry = r.json().get(str(app_id), {})
if not entry.get("success"):
return None
data = entry["data"]
po = data.get("price_overview")
result = {"name": data.get("name", "?")}
if po:
result.update(
currency=po["currency"],
initial=po["initial"] / 100,
final=po["final"] / 100,
discount_pct=po["discount_percent"],
)
else:
result.update(currency="", initial=None, final=None, discount_pct=0) # free / unreleased
return result
def itad_history(app_id):
"""Full price history for Steam via IsThereAnyDeal. Returns list of dicts."""
if not ITAD_KEY:
return None
base = "https://api.isthereanydeal.com"
r = session.get(
f"{base}/games/lookup/v1",
params={"key": ITAD_KEY, "appid": f"app/{app_id}"},
timeout=15,
)
r.raise_for_status()
j = r.json()
if not j.get("found"):
return []
game_id = j["game"]["id"]
r = session.get(
f"{base}/games/history/v2",
params={
"key": ITAD_KEY,
"id": game_id,
"country": COUNTRY.upper(),
"shops": STEAM_SHOP_ID_ITAD,
"since": "2000-01-01T00:00:00Z",
},
timeout=30,
)
r.raise_for_status()
out = []
for h in r.json():
deal = h.get("deal", {})
out.append(
{
"date": h.get("timestamp"),
"price": deal.get("price", {}).get("amount"),
"regular": deal.get("regular", {}).get("amount"),
"cut": deal.get("cut"),
}
)
return out
def cheapshark_lowest(app_id):
"""Fallback: all-time lowest price (USD) from CheapShark, no key needed."""
r = session.get(
"https://www.cheapshark.com/api/1.0/games",
params={"steamAppID": app_id},
timeout=15,
)
r.raise_for_status()
games = r.json()
if not games:
return None
r = session.get(
"https://www.cheapshark.com/api/1.0/games",
params={"id": games[0]["gameID"]},
timeout=15,
)
r.raise_for_status()
low = r.json().get("cheapestPriceEver")
if low:
return {"price_usd": float(low["price"]), "date": time.strftime("%Y-%m-%d", time.gmtime(low["date"]))}
return None
def main():
folder = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
ids = find_ids(folder)
if not ids:
print(f"No '<id>.csv' files found in {folder.resolve()}")
return
print(f"Found {len(ids)} app IDs. History source: {'IsThereAnyDeal' if ITAD_KEY else 'CheapShark (lowest only)'}\n")
summary_rows = []
history_rows = []
for app_id in ids:
try:
cur = steam_current(app_id)
except requests.RequestException as e:
print(f"[{app_id}] Steam lookup failed: {e}")
continue
if not cur:
print(f"[{app_id}] Not found on Steam store")
continue
row = {"app_id": app_id, **cur, "lowest_price": "", "lowest_date": "", "max_discount_pct": "", "times_discounted": ""}
try:
hist = itad_history(app_id)
if hist:
prices = [h for h in hist if h["price"] is not None]
if prices:
low = min(prices, key=lambda h: h["price"])
row["lowest_price"] = low["price"]
row["lowest_date"] = low["date"]
row["max_discount_pct"] = max((h["cut"] or 0) for h in prices)
row["times_discounted"] = sum(1 for h in prices if (h["cut"] or 0) > 0)
for h in hist:
history_rows.append({"app_id": app_id, "name": cur["name"], **h})
elif hist is None:
low = cheapshark_lowest(app_id)
if low:
row["lowest_price"] = low["price_usd"]
row["lowest_date"] = low["date"] + " (USD)"
except requests.RequestException as e:
print(f"[{app_id}] History lookup failed: {e}")
summary_rows.append(row)
disc = f"-{cur['discount_pct']}%" if cur["discount_pct"] else "no discount"
price = f"{cur['final']:.2f} {cur['currency']}" if cur["final"] is not None else "free/n.a."
print(f"[{app_id}] {cur['name']}: {price} ({disc}), lowest ever: {row['lowest_price'] or '?'} {row['lowest_date']}")
time.sleep(DELAY)
if summary_rows:
with open("price_summary.csv", "w", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=list(summary_rows[0].keys()))
w.writeheader()
w.writerows(summary_rows)
print("\nWrote price_summary.csv")
if history_rows:
with open("price_history.csv", "w", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=["app_id", "name", "date", "price", "regular", "cut"])
w.writeheader()
w.writerows(history_rows)
print("Wrote price_history.csv")
if __name__ == "__main__":
main()