_prep_buy.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """登录 + 钱包 + 市场 render 取价,结果写入 _tmp_session.json(读 config.json)"""
  4. import json
  5. import sys
  6. from pathlib import Path
  7. import requests
  8. ROOT = Path(__file__).resolve().parent
  9. CFG = ROOT / "config.json"
  10. OUT = ROOT / "_tmp_session.json"
  11. def load_cfg():
  12. with CFG.open("r", encoding="utf-8") as f:
  13. return json.load(f)
  14. def resolve_mafile(mafile: str) -> str:
  15. p = Path(mafile)
  16. if not p.is_absolute():
  17. p = ROOT / p
  18. return str(p.resolve())
  19. def normalize_proxy(proxy: str):
  20. raw = (proxy or "").strip()
  21. if not raw:
  22. return None
  23. if raw.lower().startswith(("http://", "https://", "socks5://", "socks4://", "socks://")):
  24. return raw
  25. return f"http://{raw}"
  26. def main() -> int:
  27. cfg = load_cfg()
  28. api = (cfg.get("api_base") or "http://localhost:5000").rstrip("/")
  29. mafile = resolve_mafile(cfg["mafile"])
  30. market = (cfg.get("market_url") or "").strip()
  31. if not market:
  32. print("config.json 需要 market_url", file=sys.stderr)
  33. return 2
  34. proxy = normalize_proxy(cfg.get("proxy") or "")
  35. proxies = {"http": proxy, "https": proxy} if proxy else None
  36. body = {
  37. "Username": cfg["username"],
  38. "Password": cfg["password"],
  39. "MaFilePath": mafile,
  40. }
  41. if proxy:
  42. body["ProxyUrl"] = proxy
  43. r = requests.post(f"{api}/login", json=body, timeout=90)
  44. print("login", r.status_code)
  45. r.raise_for_status()
  46. d = r.json()
  47. sess = d["session"]
  48. cookies = {c["name"]: c["value"] for c in d.get("cookies") or []}
  49. sls = cookies.get("steamLoginSecure") or f"{sess['steamId']}%7C%7C{sess['accessToken']}"
  50. sid = cookies.get("sessionid") or sess.get("sessionId")
  51. print("steamId", sess.get("steamId"), "sessionId", sid)
  52. wr = requests.get(
  53. "https://store.steampowered.com/api/getfundwalletinfo/?cc=us&l=english",
  54. headers={"Cookie": f"steamLoginSecure={sls}"},
  55. timeout=20,
  56. proxies=proxies,
  57. )
  58. print("wallet_http", wr.status_code, wr.text[:400])
  59. url = market.rstrip("/") + "/render/?query=&start=0&count=10&country=US&language=schinese&currency=1"
  60. cookie = f"timezoneOffset=28800,0; sessionid={sid}; steamLoginSecure={sls}; bMarketOptOut=1"
  61. rr = requests.get(
  62. url,
  63. headers={"User-Agent": "Mozilla/5.0", "Cookie": cookie, "Referer": market},
  64. timeout=30,
  65. proxies=proxies,
  66. )
  67. print("render", rr.status_code)
  68. page = rr.json()
  69. info = page.get("listinginfo") or {}
  70. print("listing_count", len(info))
  71. rows = []
  72. for lid, L in info.items():
  73. sub = int(L.get("converted_price") or 0)
  74. sf = int(L.get("converted_steam_fee") or 0)
  75. pf = int(L.get("converted_publisher_fee") or 0)
  76. rows.append((str(lid), sub, sf, pf, sub + sf + pf))
  77. rows.sort(key=lambda x: x[4])
  78. print(json.dumps(rows[:5], indent=2, ensure_ascii=False))
  79. OUT.write_text(
  80. json.dumps(
  81. {
  82. "session": sess,
  83. "steamLoginSecure": sls,
  84. "sessionId": sid,
  85. "mafile": mafile,
  86. "cheapest": rows[0] if rows else None,
  87. "market": market,
  88. },
  89. ensure_ascii=False,
  90. indent=2,
  91. ),
  92. encoding="utf-8",
  93. )
  94. print("saved", OUT)
  95. return 0
  96. if __name__ == "__main__":
  97. try:
  98. sys.stdout.reconfigure(encoding="utf-8")
  99. except Exception:
  100. pass
  101. raise SystemExit(main())