A python library to authenticate with Xbox Network via your Microsoft Account and provides Xbox related Web-API.
Find a file
renovate[bot] d03cead416
⬆️ Bump ruff to v0.15.4 (#107)
This PR contains the following updates:

| Package | Change |
[Age](https://docs.renovatebot.com/merge-confidence/) |
[Confidence](https://docs.renovatebot.com/merge-confidence/) |
|---|---|---|---|
| [ruff](https://docs.astral.sh/ruff)
([source](https://redirect.github.com/astral-sh/ruff),
[changelog](https://redirect.github.com/astral-sh/ruff/blob/main/CHANGELOG.md))
| `==0.15.3` → `==0.15.4` |
![age](https://developer.mend.io/api/mc/badges/age/pypi/ruff/0.15.4?slim=true)
|
![confidence](https://developer.mend.io/api/mc/badges/confidence/pypi/ruff/0.15.3/0.15.4?slim=true)
|

---

### Release Notes

<details>
<summary>astral-sh/ruff (ruff)</summary>

###
[`v0.15.4`](https://redirect.github.com/astral-sh/ruff/blob/HEAD/CHANGELOG.md#0154)

[Compare
Source](https://redirect.github.com/astral-sh/ruff/compare/0.15.3...0.15.4)

Released on 2026-02-26.

This is a follow-up release to 0.15.3 that resolves a panic when the new
rule `PLR1712` was enabled with any rule that analyzes definitions, such
as many of the `ANN` or `D` rules.

##### Bug fixes

- Fix panic on access to definitions after analyzing definitions
([#&#8203;23588](https://redirect.github.com/astral-sh/ruff/pull/23588))
- \[`pyflakes`] Suppress false positive in `F821` for names used before
`del` in stub files
([#&#8203;23550](https://redirect.github.com/astral-sh/ruff/pull/23550))

##### Documentation

- Clarify first-party import detection in Ruff
([#&#8203;23591](https://redirect.github.com/astral-sh/ruff/pull/23591))
- Fix incorrect `import-heading` example
([#&#8203;23568](https://redirect.github.com/astral-sh/ruff/pull/23568))

##### Contributors

- [@&#8203;stakeswky](https://redirect.github.com/stakeswky)
- [@&#8203;ntBre](https://redirect.github.com/ntBre)
- [@&#8203;thejcannon](https://redirect.github.com/thejcannon)
- [@&#8203;GeObts](https://redirect.github.com/GeObts)

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined),
Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you
are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the
rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update
again.

---

- [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check
this box

---

This PR was generated by [Mend Renovate](https://mend.io/renovate/).
View the [repository job
log](https://developer.mend.io/github/tr4nt0r/python-xbox).

<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0My4zNi4yIiwidXBkYXRlZEluVmVyIjoiNDMuMzYuMiIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOlsiOnJlY3ljbGU6IGRlcGVuZGVuY2llcyIsIjpzbmFrZTogcHl0aG9uIl19-->

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-02-28 02:17:17 +01:00
.github Remove buymeacoffee (#105) 2026-02-26 10:21:08 +01:00
docs Add documentation workflow and mkdocs config (#48) 2025-11-09 16:23:19 +01:00
src/pythonxbox fix(people): correct friends list API endpoint for target users (#103) 2026-02-28 02:16:42 +01:00
tests Replace ecdsa with cryptography (#104) 2026-02-26 09:55:48 +01:00
.gitignore Add documentation workflow and mkdocs config (#48) 2025-11-09 16:23:19 +01:00
.pre-commit-config.yaml Remove bandit/pyupgrade in pre-commit (#24) 2025-10-30 22:40:42 +01:00
LICENSE Update authors and project classifiers (#27) 2025-10-31 02:51:42 +01:00
mkdocs.yml Add documentation workflow and mkdocs config (#48) 2025-11-09 16:23:19 +01:00
pyproject.toml ⬆️ Bump ruff to v0.15.4 (#107) 2026-02-28 02:17:17 +01:00
README.md Remove buymeacoffee (#105) 2026-02-26 10:21:08 +01:00
readme_example.py Enable ruff ANN rule and fix annotations (#25) 2025-10-31 02:24:18 +01:00
renovate.json Update Renovate to use best-practices preset and enhance commit message formatting (#60) 2025-11-12 23:34:20 +01:00

python-xbox

PyPi - latest Build codecov PyPI - Downloads GitHub Sponsor

python-xbox is a python library to authenticate with Xbox Network via your Microsoft Account and provides Xbox related Web-API.

Authentication is supported via OAuth2.

  • Register a new application in Azure AD
    • Name your app
    • Select "Personal Microsoft accounts only" under supported account types
    • Add http://localhost/auth/callback as a Redirect URI of type "Web"
  • Copy your Application (client) ID for later use
  • On the App Page, navigate to "Certificates & secrets"
    • Generate a new client secret and save for later use

Dependencies

  • Python >= 3.11

How to use

Install

pip install python-xbox

Authentication

Note

You must use non child account (> 18 years old)

Token save location: If tokenfile is not provided via cmdline, fallback of <platformdirs.user_data_dir>/tokens.json is used as save-location

Specifically:

Windows: C:\\Users\\<username>\\AppData\\Local\\OpenXbox\\xbox

Mac OSX: /Users/<username>/Library/Application Support/xbox/tokens.json

Linux: /home/<username>/.local/share/xbox

For more information, see: https://pypi.org/project/platformdirs and module: python-xbox.scripts.constants

xbox-authenticate --client-id <client-id> --client-secret <client-secret>

Example: Search Xbox Live via cmdline tool

  # Search Xbox One Catalog
  xbox-searchlive "Some game title"

API usage

import asyncio
import sys

from httpx import HTTPStatusError

from pythonxbox.api.client import XboxLiveClient
from pythonxbox.authentication.manager import AuthenticationManager
from pythonxbox.authentication.models import OAuth2TokenResponse
from pythonxbox.common.signed_session import SignedSession
from pythonxbox.scripts import CLIENT_ID, CLIENT_SECRET, TOKENS_FILE

"""
This uses the global default client identification by OpenXbox
You can supply your own parameters here if you are permitted to create
new Microsoft OAuth Apps and know what you are doing
"""
client_id = CLIENT_ID
client_secret = CLIENT_SECRET
tokens_file = TOKENS_FILE

"""
For doing authentication, see pythonxbox/scripts/authenticate.py
"""


async def async_main():
    # Create a HTTP client session
    async with SignedSession() as session:
        """
        Initialize with global OAUTH parameters from above
        """
        auth_mgr = AuthenticationManager(session, client_id, client_secret, "")

        """
        Read in tokens that you received from the `xbox-authenticate`-script previously
        See `pythonxbox/scripts/authenticate.py`
        """
        try:
            with open(tokens_file) as f:
                tokens = f.read()
            # Assign gathered tokens
            auth_mgr.oauth = OAuth2TokenResponse.model_validate_json(tokens)
        except FileNotFoundError as e:
            print(
                f"File {tokens_file} isn`t found or it doesn`t contain tokens! err={e}"
            )
            print("Authorizing via OAUTH")
            url = auth_mgr.generate_authorization_url()
            print(f"Auth via URL: {url}")
            authorization_code = input("Enter authorization code> ")
            tokens = await auth_mgr.request_oauth_token(authorization_code)
            auth_mgr.oauth = tokens

        """
        Refresh tokens, just in case
        You could also manually check the token lifetimes and just refresh them
        if they are close to expiry
        """
        try:
            await auth_mgr.refresh_tokens()
        except HTTPStatusError as e:
            print(
                f"""
                Could not refresh tokens from {tokens_file}, err={e}\n
                You might have to delete the tokens file and re-authenticate 
                if refresh token is expired
            """
            )
            sys.exit(-1)

        # Save the refreshed/updated tokens
        with open(tokens_file, mode="w") as f:
            f.write(auth_mgr.oauth.json())
        print(f"Refreshed tokens in {tokens_file}!")

        """
        Construct the Xbox API client from AuthenticationManager instance
        """
        xbl_client = XboxLiveClient(auth_mgr)

        """
        Some example API calls
        """
        # Get friendslist
        friendslist = await xbl_client.people.get_friends_own()
        print(f"Your friends: {friendslist}\n")

        # Get presence status (by list of XUID)
        presence = await xbl_client.presence.get_presence_batch(
            ["2533274794093122", "2533274807551369"]
        )
        print(f"Statuses of some random players by XUID: {presence}\n")

        # Get messages
        messages = await xbl_client.message.get_inbox()
        print(f"Your messages: {messages}\n")

        # Get profile by GT
        profile = await xbl_client.profile.get_profile_by_gamertag("SomeGamertag")
        print(f"Profile under SomeGamertag gamer tag: {profile}\n")


asyncio.run(async_main())

Contribute

  • Report bugs/suggest features
  • Add/update docs
  • Add additional xbox live endpoints

Credits

This library is derived from xbox-webapi library from the OpenXbox project The authentication code is based on joealcorn/xbox

Informations on endpoints gathered from:

Disclaimer

Xbox, Xbox One, Smartglass and Xbox Live are trademarks of Microsoft Corporation. Team OpenXbox is in no way endorsed by or affiliated with Microsoft Corporation, or any associated subsidiaries, logos or trademarks.