Metadata-Version: 2.1
Name: humblebundle.py
Version: 1.0.1
Summary: Unofficial, typed Python client for humblebundle.com
Author: ghostapps
License: MIT License
        
        Copyright (c) 2026 ghostapps
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
Project-URL: Homepage, https://github.com/markemicek/humblebundle.py
Project-URL: Source, https://github.com/markemicek/humblebundle.py
Project-URL: Issues, https://github.com/markemicek/humblebundle.py/issues
Project-URL: Changelog, https://github.com/markemicek/humblebundle.py/blob/master/CHANGELOG.md
Keywords: humblebundle,humble-choice,bundles,games,scraper,api,client
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Games/Entertainment
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Provides-Extra: dev
License-File: LICENSE.txt

# humblebundle.py

[![PyPI](https://img.shields.io/pypi/v/humblebundle.py.svg)](https://pypi.org/project/humblebundle.py/)
[![Python versions](https://img.shields.io/pypi/pyversions/humblebundle.py.svg)](https://pypi.org/project/humblebundle.py/)
[![Typed](https://img.shields.io/badge/typing-typed-blue.svg)](https://peps.python.org/pep-0561/)
[![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE.txt)

Unofficial, typed Python client for [humblebundle.com](https://www.humblebundle.com).

It answers five questions, and nothing else:

| Question | Call |
| --- | --- |
| Which bundles are live right now? | `client.bundles("games")` |
| What is inside one bundle? | `client.bundle("survival-fittest")` / `client.items(...)` |
| What is in this month's Humble Choice? | `client.choices()` |
| What is in the Humble Store? | `client.store()` / `client.store_search("witcher")` / `client.store_product("cult-of-the-lamb")` |
| What did the site actually send? | `product.raw` |

Everything is immutable, typed, JSON-serialisable and documented in-place — the
library is designed to be used by people and by AI agents (see
[`llms.txt`](llms.txt) and [`AGENTS.md`](AGENTS.md)).

```bash
pip install humblebundle.py
```

Requires Python 3.10+. The only runtime dependency is `requests`.

## Quick start

```python
from humblebundle import HumbleBundleClient

client = HumbleBundleClient()          # reuse it; it holds a pooled HTTP session

for bundle in client.bundles("games").values():
    ends = bundle.end_date.date() if bundle.end_date else "no end date"
    print(f"{bundle.title} — {bundle.price} — ends {ends}")

items = client.items("survival-fittest")
for item in items.values():
    print(item.title, item.msrp, ", ".join(item.developers))

choice = client.choices()
for game in choice.values():
    print(game.title, game.price)

store = client.store()
for section in store.sections:
    print(section.title, len(section.products))

for product in client.store_search("witcher", sort="top-discounts").values():
    print(product.title, product.price, f"-{product.discount_percent}%")

game = client.store_product("cult-of-the-lamb")
print(game.title, game.developers, game.genres, game.price)
```

Prefer a context manager when you want the session closed deterministically:

```python
with HumbleBundleClient(timeout=10) as client:
    print(client.bundles("books").titles)
```

Short scripts can skip the class entirely:

```python
import humblebundle

print(humblebundle.bundles("books").titles)
print(humblebundle.items("survival-fittest").first)
```

## What you get back

`bundles()` returns a `ProductCollection[Bundle]`; `items()` returns a
`ProductCollection[BundleItem]`; `choices()` returns a `HumbleChoice`, which *is*
a mapping of game key to `ChoiceGame`; `store()` returns a `Store` and
`store_search()` a `StoreSearch`, both mappings of product key to
`StoreProduct`, and `store_product()` returns a single `StoreProductDetail`.

`ProductCollection` is a read-only mapping with extras:

```python
bundles = client.bundles(["games", "books"])

len(bundles)                       # count
bundles["some_bundle"]             # lookup by key
bundles.first                      # first product or None
bundles.titles                     # {key: title}
bundles.search("survival")         # case-insensitive filter, returns a new collection
bundles.to_dict()                  # JSON-ready nested dict
```

### Models

| Model | Returned by | Highlights |
| --- | --- | --- |
| `Bundle` | `bundles()`, `bundle()` | `title`, `price`, `retail_value`, `included_item_titles`, `platforms`, `end_date`, `tiers`, `items()` |
| `BundleItem` | `items()` | `title`, `description`, `msrp`, `developers`, `publishers`, `platforms`, `delivery_methods`, `media`, `tier_key` |
| `ChoiceGame` | `choices()` | `title`, `price`, `developers`, `genres`, `platforms`, `media`, `end_date` |
| `Store` | `store()` | `url`, `sections`, `promotions`, `products`, `section(name)` |
| `StoreSection` | `Store.sections` | `key`, `title`, `layout`, `card_count`, `products` |
| `StoreProduct` | `Store`, `StoreSearch` | `title`, `price`, `base_price`, `discount_percent`, `platforms`, `delivery_methods`, `on_sale` |
| `StoreProductDetail` | `store_product()` | everything in `StoreProduct` plus `description`, `developers`, `publishers`, `genres`, `media`, `editions`, `distributions`, `critic_reviews`, ratings, requirements |
| `StoreSearch` | `store_search()` | `query`, `page`, `pages`, `total`, `sort`, `refinements`, `facets`, `next_page()` |
| `StoreSort` | `store_search(sort=...)` | `RELEVANCE`, `TOP_DISCOUNTS`, `ALPHABETICAL`, `NEWEST` |
| `Money` | `price` / `msrp` / `retail_value` | `amount` (float), `currency` (ISO-4217) |
| `Tier` | `Bundle.tiers` | `key`, `price`, `items` |

Every model:

* is **frozen** — safe to share, cache and compare;
* is **mapping-like** — `product["title"]`, `dict(product)`, `product.keys()`;
* is **JSON-ready** — `to_dict()` converts `Money` to `{"amount", "currency"}` and
  dates to ISO-8601 strings;
* keeps the source payload in `.raw` and exposes it in JSON with
  `to_dict(include_raw=True)`.

Dates are timezone-aware UTC `datetime` objects. `Bundle.is_expired` and
`Bundle.supports("windows")` are provided for convenience.

`humblebundle schema` prints a machine-readable description of every model and
field — handy for LLM tooling and for keeping docs honest.

## Command line

Installing the package adds a `humblebundle` command:

```bash
humblebundle bundles games
humblebundle bundles books software --limit 5
humblebundle bundle survival-fittest
humblebundle bundle survival-fittest --items --fields key,title,msrp
humblebundle items survival-fittest --json
humblebundle choices --json
humblebundle store
humblebundle store --section featured-deals --limit 10
humblebundle store-product cult-of-the-lamb --json
humblebundle store-search witcher --sort top-discounts --genre rpg
humblebundle schema                # JSON model description for AI agents
humblebundle --version
```

Output is a human-readable table by default; `--json` prints a stable payload
with `--fields` projection and `--raw` for the untouched source data. Errors go
to stderr, exit code `0` on success and `1` when the library raises. The same
command works without installation via `python -m humblebundle`.

## Error handling

```python
from humblebundle import (
    AgeVerificationError,
    AuthenticationError,
    BundleNotFoundError,
    FetchError,
    HumbleBundleError,
    PageDataError,
    RateLimitError,
    StoreProductNotFoundError,
)

try:
    bundle = client.bundle("survival-fittest")
except RateLimitError as exc:
    print("slow down:", exc.status_code, exc.url)
except BundleNotFoundError:
    print("that bundle page had no bundle data")
except PageDataError:
    print("humblebundle.com changed its page structure")
except FetchError as exc:
    print("network or HTTP failure:", exc.status_code, exc.url)
except HumbleBundleError:
    print("anything else from this library")
```

Store-specific failures are `StoreProductNotFoundError` (the product page had no
product data) and `AgeVerificationError` (an age-gated product could not be
unlocked). `FetchError.status_code` / `.url` carry the offending response
details.

## Configuration

```python
HumbleBundleClient(
    timeout=30.0,        # per-request timeout, seconds
    retries=3,           # extra attempts for 429/5xx and connection errors
    user_agent=None,     # override the browser User-Agent
    session=None,        # reuse your own requests.Session
    source=None,         # replace the transport (any object with get_text(path))
    base_url=...,        # point at a mirror
    age_gate_birthdate="1990-01-01",   # answer the store's age gate automatically
    store_search_action=None,          # override the discovered search action id
)
```

Age-gated store products (adult titles) show a birthday form instead of the
product. The client answers it with a plain cookie and re-fetches the page; pass
`age_gate_birthdate=None` to opt out and get `AgeVerificationError` instead, or
`store_product(..., birthdate="YYYY-MM-DD")` to answer for one product only.

Transient failures (HTTP 429/500/502/503/504, connection errors, timeouts) are
retried with exponential backoff and honour `Retry-After`. Permanent failures
raise `FetchError`/`RateLimitError` immediately.

### Async

For `asyncio` code, `AsyncHumbleBundleClient` runs the synchronous transport in a
worker thread, so the event loop is never blocked:

```python
import asyncio
from humblebundle import AsyncHumbleBundleClient

async def main():
    async with AsyncHumbleBundleClient(timeout=15) as client:
        bundles, choice = await asyncio.gather(
            client.bundles("games"),
            client.choices(),
        )
        print(len(bundles), len(choice))

asyncio.run(main())
```

### Logging

The library never configures logging and never prints. Enable diagnostics when
you want them:

```python
import humblebundle

humblebundle.configure_logging("DEBUG")   # stderr handler on the "humblebundle" logger
humblebundle.silence()                    # back to silent
```

## Account access (optional)

Public data needs no login. `client.login(username, password, authy_token=...)`
exists for account-specific pages and mirrors Humble's Android app endpoints; it
may require a 2FA token or a solved reCAPTCHA. Prefer public data.

## How it works

humblebundle.com is a Next.js (App Router) application. Page data is streamed
inside the React Server Components ("flight") payload as a series of
`self.__next_f.push([1, "..."])` calls rather than in
`<script type="application/json">` islands.

```mermaid
flowchart LR
    A[HttpClient] -->|HTML| B[_rsc.extract_flight]
    B -->|flight stream| C[_rsc.parse_flight]
    C -->|rows| D[_rsc.resolve]
    D -->|plain dicts| E[_parser]
    E -->|feed / tiers / products| F[models]
    F --> G[ProductCollection / HumbleChoice / Store]
```

Store search is the one exception: the site answers it through a Next.js
*server action* (a multipart POST to `/search` that carries a build-specific
action id). The id is read from the JavaScript chunks on first use and cached,
and the POST is sent with `http.client` because Cloudflare blocks the
`requests`/`urllib3` TLS fingerprint on that endpoint.

* `_rsc` — extracts, splits and resolves the flight payload (no Humble-specific
  knowledge);
* `_parser` — locates the blocks we need (`feedItems`, `tiers.bundleItems`,
  `subscriptionProducts`);
* `models` — typed, frozen value objects;
* `client` / `get` — the public API.

## Migrating from 0.2

`humblebundle.get.bundles(...)`, `get.bundle(...)` and `get.choices(...)` still
work, and top-level `humblebundle.bundles/bundle/choices` are unchanged. The
changes worth knowing:

| 0.2 | 1.0 |
| --- | --- |
| `_Product` objects with dynamic attributes | `Bundle` / `BundleItem` / `ChoiceGame` (declared fields, same attribute names) |
| `product.price` was a `float` | `product.price` is `Money`; use `product.price.amount` |
| `bundle.stepin()` | `bundle.items()` (`stepin()` still works, emits `DeprecationWarning`) |
| `bundles()` returned `dict` | returns `ProductCollection` (a read-only `Mapping`; `dict(bundles)` works) |
| `choices()` returned `dict` | returns `HumbleChoice` (a `Mapping`) |
| title-cased aliases (`Title`, `highlights`) | kept as properties where they existed |

See [CHANGELOG.md](CHANGELOG.md) for the full list.

## Development

```bash
python -m pip install -e ".[dev]"
python -m pytest
python -m ruff check .
python -m mypy
```

The test suite is hermetic: it builds synthetic Next.js payloads and never
touches the network. See [CONTRIBUTING.md](CONTRIBUTING.md).

## Notes and fair use

- Only public page data is read; no login or account access is required.
- Only the current Humble Choice month is available — Humble removed the
  per-month pages, so `choices(month=..., year=...)` records a label but cannot
  fetch history.
- humblebundle.com asks automated clients to be considerate: keep request volume
  low, reuse one client, and cache results in your own code.
- This project is not affiliated with Humble Bundle.

## License

MIT — see [LICENSE.txt](LICENSE.txt).
