Metadata-Version: 2.1
Name: humblebundle.py
Version: 2.1.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
License-File: LICENSE.txt
Requires-Dist: requests >=2.28
Provides-Extra: dev
Requires-Dist: pytest >=8 ; extra == 'dev'
Requires-Dist: pytest-cov >=5 ; extra == 'dev'
Requires-Dist: mypy ==2.4.1 ; extra == 'dev'
Requires-Dist: ruff ==0.17.6 ; extra == 'dev'

# 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/)
[![CI](https://github.com/markemicek/humblebundle.py/actions/workflows/ci.yml/badge.svg)](https://github.com/markemicek/humblebundle.py/actions/workflows/ci.yml)
[![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)](https://github.com/markemicek/humblebundle.py/blob/master/LICENSE.txt)

Unofficial, typed Python client for [Humble Bundle](https://www.humblebundle.com).
It does two things:

- **Extracts Humble Bundle data** — live bundles, bundle contents, Humble
  Choice, the store catalogue and product pages, and (with a session) your own
  library, keys, orders and wallet.
- **Downloads what you bought** — resolves the signed URLs for an owned item and
  writes its files to disk, verified against the checksums the site publishes.

Everything comes back as a frozen, typed, mapping-like, JSON-ready model. No API
key and no browser automation; the only runtime dependency is `requests`.

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

Requires Python 3.10 or newer.

## What it does

| You want | Call |
| --- | --- |
| the bundles on sale right now | `client.bundles("games")` |
| what is inside one bundle | `client.items("survival-fittest")` |
| this month's Humble Choice | `client.choices()` |
| the store catalogue, a search, or one product | `client.store()`, `client.store_search("witcher")`, `client.store_product("cult-of-the-lamb")` |
| what you own, with keys and files | `client.library()`, `client.library_item(id)` |
| signed URLs for one owned item | `client.download_manifest(id)` |
| those files written to disk | `client.download(id, "./library")` |
| your order history and wallet balance | `client.orders()`, `client.wallet()`, `client.account()` |

Public data needs no sign-in. The account rows need a session — see
[Signing in](#signing-in).

## 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}")

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

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

Prefer a context manager when the session should close deterministically:

```python
with HumbleBundleClient(timeout=10) as client:
    print(client.store_search("hades", sort="top-discounts").titles)
```

Short scripts can skip the class entirely:

```python
import humblebundle

print(humblebundle.bundles("books").titles)
```

## Read the data

`bundles()` and `items()` return a `ProductCollection[T]` — a read-only mapping
with helpers. `choices()` returns a `HumbleChoice`, `store()` a `Store`,
`store_search()` a `StoreSearch`, `library()` a `Library`, and the single-record
calls return one model each.

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

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

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

results = client.store_search("witcher", sort="top-discounts", genres=["rpg"])
print(results.total, results.pages, results.facets["genres"])
for entry in results.values():
    print(entry.title, entry.price, f"-{entry.discount_percent}%")
```

Every model:

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

Dates are timezone-aware UTC `datetime` objects. See the
[API reference](https://github.com/markemicek/humblebundle.py/blob/master/docs/api.md#models)
for every model and field, or run `humblebundle schema` for a machine-readable
description.

## Download your purchases

Two levels, so you choose how much the library does for you.

**Get the URLs.** `download_manifest()` fetches and signs, and does nothing else:

```python
manifest = client.download_manifest("Project Winter Soundtrack")

manifest.expires_at
for entry in manifest.files:
    print(entry.filename, entry.size, entry.url, entry.torrent_url)
```

**Or write the files.** `download()` does both steps and returns a report:

```python
report = client.download("Project Winter Soundtrack", "./library")

print(report.ok, len(report.saved), report.bytes_written)
for entry in report.failed:            # retry only what failed
    print(entry.filename, entry.error)
```

Each file is streamed into `name.part`, hashed while it downloads, checked
against the published `sha1`/`md5`, and moved into place with `os.replace` only
when complete — so an interrupted transfer never leaves a truncated file under
the real name. A failed file is recorded on `report.failed` instead of raising,
so one dead link does not lose the rest of the item.

For a reusable policy, build a `Downloader` once and reuse it:

```python
from humblebundle import Downloader

downloader = Downloader(client, overwrite=False, verify=True, progress=print)
report = downloader.save(manifest, "./library", files=["Album.zip"])
```

Owned items can also carry **product keys**, wrapped in `Secret`: `repr`, logs
and `to_dict()` show `***`. Ask explicitly:

```python
item = client.library_item("01234567-0000-4000-8000-000000000000")
item.has_downloads, item.files      # files with sizes and md5/sha1
item.has_keys, item.product_keys    # keys and redemption URLs
item.product_keys[0].reveal()       # "XXXXX-XXXXX-XXXXX"
```

From the shell, `humblebundle library download ITEM --to DIR` is the same
downloader: it skips existing files unless `--overwrite`, refuses a name that
would escape `DIR`, and reports what was written.

## Examples

**Browse and search the store**

```python
store = client.store()
featured = store.section("featured-deals")     # key, title or hyphenated title
for product in featured.products:
    print(product.title, product.price, product.discount_percent)

detail = client.store_product("cult-of-the-lamb")
print(detail.title, detail.developers, detail.genres, detail.price)
print(detail.description_text[:200])
```

**Your library and orders** (needs a session)

```python
from humblebundle import LibrarySort, OrderSort

library = client.library(sort=LibrarySort.TITLE_A_TO_Z, per_page=100)
print(library.total, len(library.titles), library.has_next)

history = client.orders(sort=OrderSort.TOTAL)
order = history.first
print(order.order_number, order.total, order.donations)

print(client.wallet().balance)          # 12.34 USD
```

**Async**

```python
import asyncio
from humblebundle import AsyncHumbleBundleClient

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

asyncio.run(main())
```

**Failures are typed**

```python
from humblebundle import BundleNotFoundError, FetchError, RateLimitError

try:
    client.bundle("survival-fittest")
except RateLimitError as exc:
    print("slow down:", exc.status_code)
except BundleNotFoundError:
    print("that bundle is not live")
except FetchError as exc:
    print("http failure:", exc.status_code, exc.url)
```

## Command line

Installing the package adds `humblebundle` (`python -m humblebundle` works too).
The grammar is `humblebundle NOUN VERB [ARGS]`, like `gh` or `kubectl`, so the
record is always positional:

```bash
humblebundle bundles list games --limit 5
humblebundle bundles items survival-fittest
humblebundle bundles show survival-fittest -o json
humblebundle choices list
humblebundle store list --section featured-deals
humblebundle store search witcher --sort top-discounts --genre rpg
humblebundle store show cult-of-the-lamb
humblebundle schema
```

With a session, the same nouns read your account and download files:

```bash
humblebundle library list --query soundtrack --sort aToZ
humblebundle library list --kind bundle
humblebundle library show 01234567-0000-4000-8000-000000000000 --reveal
humblebundle library download "Project Winter Soundtrack" --to ./music --file flac
humblebundle orders list --sort total
humblebundle wallet
```

Output is a table by default; `-o json`, `-o jsonl` and `-o tsv` are for scripts,
and `--fields`, `--limit`, `--raw` and `-q` trim it. Colour follows the terminal
and honours `NO_COLOR`.

Errors go to stderr as one line, with an exit code that says what happened: `2`
usage, `3` sign-in, `4` not found, `5` network, `1` anything else. The
[CLI reference](https://github.com/markemicek/humblebundle.py/blob/master/docs/cli.md)
covers every command and option.

## Signing in

Public pages need no sign-in. Account pages require a session, and Humble Bundle
signs in through Ory (Kratos) at `auth.humblebundle.com`. Two headless options:

```python
from humblebundle import CookieAuthenticator, HumbleBundleClient, SessionManager

# Recommended: a session cookie copied from a signed-in browser.
client = HumbleBundleClient(
    auth=SessionManager(CookieAuthenticator.from_header("ory_session_...=abc123"))
)

# Or a password, used for one handshake and never stored.
client = HumbleBundleClient.authenticated("me@example.com", "...", totp=None)

print(client.auth_status())          # secret-free
```

```bash
humblebundle auth login --cookie-stdin          # paste the cookie
humblebundle auth login --email me@example.com --password-stdin --keep-alive
humblebundle session --email me@example.com --password-stdin
```

Secrets (`Secret`) render as `***` in `repr`, logs and JSON. Nothing is written
to disk: a session lives in memory for the life of the process. Accounts created
through a third-party button have no password — sign in through the website and
hand the cookie to `CookieAuthenticator`. See the
[authentication docs](https://github.com/markemicek/humblebundle.py/blob/master/docs/api.md#authentication).

## Documentation

| Page | What is in it |
| --- | --- |
| [Quick start](https://github.com/markemicek/humblebundle.py/blob/master/docs/quickstart.md) | worked examples for every public call |
| [API reference](https://github.com/markemicek/humblebundle.py/blob/master/docs/api.md) | every method, model and field |
| [CLI reference](https://github.com/markemicek/humblebundle.py/blob/master/docs/cli.md) | every command, option and exit code |
| [Architecture](https://github.com/markemicek/humblebundle.py/blob/master/docs/architecture.md) | how parsing, models and auth fit together |
| [llms.txt](https://github.com/markemicek/humblebundle.py/blob/master/llms.txt) | machine-oriented API summary for AI agents |
| [CHANGELOG](https://github.com/markemicek/humblebundle.py/blob/master/CHANGELOG.md) | release history |
| [CONTRIBUTING](https://github.com/markemicek/humblebundle.py/blob/master/CONTRIBUTING.md) | development setup and conventions |

## Development

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

The test suite is hermetic: it builds synthetic Next.js payloads and never
touches the network.

## Fair use

- Unofficial project; not affiliated with Humble Bundle.
- Signed-out use reads only public page data.
- Signed-in use reads only your own account, with a session you supply. Nothing
  is purchased, redeemed or modified.
- humblebundle.com's `robots.txt` disallows automated retrieval under `/auth/`,
  `/api/`, `/home` and `/user`, so authenticated use goes against that policy.
  Decide for yourself, keep request volume low, reuse one client, and cache.
- Only the current Humble Choice month is published, and the store wishlist is
  switched off site-wide (`client.wishlist()` raises `WishlistUnavailableError`).
- A site change can break any of this.

## License

MIT — see [LICENSE.txt](https://github.com/markemicek/humblebundle.py/blob/master/LICENSE.txt).
