xbox-webapi


Namexbox-webapi JSON
Version 2.1.0 PyPI version JSON
download
home_page
SummaryA library to authenticate with Windows Live/Xbox Live and use their API
upload_time2023-11-25 22:24:54
maintainer
docs_urlNone
authorOpenXbox
requires_python>=3.8
licenseGPL
keywords xbox one live api
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Xbox-WebAPI

[![PyPi - latest](https://img.shields.io/pypi/v/xbox-webapi.svg)](https://pypi.python.org/pypi/xbox-webapi/)
[![Documentation status](https://readthedocs.org/projects/xbox-webapi-python/badge/?version=latest)](http://xbox-webapi-python.readthedocs.io/en/latest/?badge=latest)
[![Build status](https://img.shields.io/github/actions/workflow/status/OpenXbox/xbox-webapi-python/build.yml?branch=master)](https://github.com/OpenXbox/xbox-webapi-python/actions?query=workflow%3Abuild)
[![Discord chat channel](https://img.shields.io/badge/discord-OpenXbox-blue.svg)](https://openxbox.org/discord)

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

Authentication is supported via OAuth2.

- Register a new application in [Azure AD](https://portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/ApplicationsListBlade)
  - 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.8

## How to use

Install

```text
pip install xbox-webapi
```

Authentication

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

Token save location: If tokenfile is not provided via cmdline, fallback of `<appdirs.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/appdirs> and module: `xbox.webapi.scripts.constants`

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

Example: Search Xbox Live via cmdline tool

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

API usage

```py
import asyncio
import sys

from httpx import HTTPStatusError

from xbox.webapi.api.client import XboxLiveClient
from xbox.webapi.authentication.manager import AuthenticationManager
from xbox.webapi.authentication.models import OAuth2TokenResponse
from xbox.webapi.common.signed_session import SignedSession
from xbox.webapi.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 xbox/webapi/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 `xbox/webapi/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 package uses parts of [Cookiecutter](https://github.com/audreyr/cookiecutter)
and the [audreyr/cookiecutter-pypackage](https://github.com/audreyr/cookiecutter-pypackage) project template.
The authentication code is based on [joealcorn/xbox](https://github.com/joealcorn/xbox)

Informations on endpoints gathered from:

- [XboxLive REST Reference](https://docs.microsoft.com/en-us/windows/uwp/xbox-live/xbox-live-rest/atoc-xboxlivews-reference)
- [XboxLiveTraceAnalyzer APIMap](https://github.com/Microsoft/xbox-live-trace-analyzer/blob/master/Source/XboxLiveTraceAnalyzer.APIMap.csv)
- [Xbox Live Service API](https://github.com/Microsoft/xbox-live-api)

## 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.

            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "xbox-webapi",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": "",
    "keywords": "xbox one live api",
    "author": "OpenXbox",
    "author_email": "",
    "download_url": "https://files.pythonhosted.org/packages/f5/5a/7af2bdd9725ebf905adb89fdcc78bfaae2e16ea7637db294febbbea443f6/xbox-webapi-2.1.0.tar.gz",
    "platform": null,
    "description": "# Xbox-WebAPI\n\n[![PyPi - latest](https://img.shields.io/pypi/v/xbox-webapi.svg)](https://pypi.python.org/pypi/xbox-webapi/)\n[![Documentation status](https://readthedocs.org/projects/xbox-webapi-python/badge/?version=latest)](http://xbox-webapi-python.readthedocs.io/en/latest/?badge=latest)\n[![Build status](https://img.shields.io/github/actions/workflow/status/OpenXbox/xbox-webapi-python/build.yml?branch=master)](https://github.com/OpenXbox/xbox-webapi-python/actions?query=workflow%3Abuild)\n[![Discord chat channel](https://img.shields.io/badge/discord-OpenXbox-blue.svg)](https://openxbox.org/discord)\n\nXbox-WebAPI is a python library to authenticate with Xbox Live via your Microsoft Account and provides Xbox related Web-API.\n\nAuthentication is supported via OAuth2.\n\n- Register a new application in [Azure AD](https://portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/ApplicationsListBlade)\n  - Name your app\n  - Select \"Personal Microsoft accounts only\" under supported account types\n  - Add <http://localhost/auth/callback> as a Redirect URI of type \"Web\"\n- Copy your Application (client) ID for later use\n- On the App Page, navigate to \"Certificates & secrets\"\n  - Generate a new client secret and save for later use\n\n## Dependencies\n\n- Python >= 3.8\n\n## How to use\n\nInstall\n\n```text\npip install xbox-webapi\n```\n\nAuthentication\n\n**Note: You must use non child account (> 18 years old)**\n\nToken save location: If tokenfile is not provided via cmdline, fallback of `<appdirs.user_data_dir>/tokens.json` is used as save-location\n\nSpecifically:\n\nWindows: `C:\\\\Users\\\\<username>\\\\AppData\\\\Local\\\\OpenXbox\\\\xbox`\n\nMac OSX: `/Users/<username>/Library/Application Support/xbox/tokens.json`\n\nLinux: `/home/<username>/.local/share/xbox`\n\nFor more information, see: <https://pypi.org/project/appdirs> and module: `xbox.webapi.scripts.constants`\n\n```\nxbox-authenticate --client-id <client-id> --client-secret <client-secret>\n```\n\nExample: Search Xbox Live via cmdline tool\n\n```text\n  # Search Xbox One Catalog\n  xbox-searchlive \"Some game title\"\n```\n\nAPI usage\n\n```py\nimport asyncio\nimport sys\n\nfrom httpx import HTTPStatusError\n\nfrom xbox.webapi.api.client import XboxLiveClient\nfrom xbox.webapi.authentication.manager import AuthenticationManager\nfrom xbox.webapi.authentication.models import OAuth2TokenResponse\nfrom xbox.webapi.common.signed_session import SignedSession\nfrom xbox.webapi.scripts import CLIENT_ID, CLIENT_SECRET, TOKENS_FILE\n\n\"\"\"\nThis uses the global default client identification by OpenXbox\nYou can supply your own parameters here if you are permitted to create\nnew Microsoft OAuth Apps and know what you are doing\n\"\"\"\nclient_id = CLIENT_ID\nclient_secret = CLIENT_SECRET\ntokens_file = TOKENS_FILE\n\n\"\"\"\nFor doing authentication, see xbox/webapi/scripts/authenticate.py\n\"\"\"\n\n\nasync def async_main():\n    # Create a HTTP client session\n    async with SignedSession() as session:\n        \"\"\"\n        Initialize with global OAUTH parameters from above\n        \"\"\"\n        auth_mgr = AuthenticationManager(session, client_id, client_secret, \"\")\n\n        \"\"\"\n        Read in tokens that you received from the `xbox-authenticate`-script previously\n        See `xbox/webapi/scripts/authenticate.py`\n        \"\"\"\n        try:\n            with open(tokens_file) as f:\n                tokens = f.read()\n            # Assign gathered tokens\n            auth_mgr.oauth = OAuth2TokenResponse.model_validate_json(tokens)\n        except FileNotFoundError as e:\n            print(\n                f\"File {tokens_file} isn`t found or it doesn`t contain tokens! err={e}\"\n            )\n            print(\"Authorizing via OAUTH\")\n            url = auth_mgr.generate_authorization_url()\n            print(f\"Auth via URL: {url}\")\n            authorization_code = input(\"Enter authorization code> \")\n            tokens = await auth_mgr.request_oauth_token(authorization_code)\n            auth_mgr.oauth = tokens\n\n        \"\"\"\n        Refresh tokens, just in case\n        You could also manually check the token lifetimes and just refresh them\n        if they are close to expiry\n        \"\"\"\n        try:\n            await auth_mgr.refresh_tokens()\n        except HTTPStatusError as e:\n            print(\n                f\"\"\"\n                Could not refresh tokens from {tokens_file}, err={e}\\n\n                You might have to delete the tokens file and re-authenticate \n                if refresh token is expired\n            \"\"\"\n            )\n            sys.exit(-1)\n\n        # Save the refreshed/updated tokens\n        with open(tokens_file, mode=\"w\") as f:\n            f.write(auth_mgr.oauth.json())\n        print(f\"Refreshed tokens in {tokens_file}!\")\n\n        \"\"\"\n        Construct the Xbox API client from AuthenticationManager instance\n        \"\"\"\n        xbl_client = XboxLiveClient(auth_mgr)\n\n        \"\"\"\n        Some example API calls\n        \"\"\"\n        # Get friendslist\n        friendslist = await xbl_client.people.get_friends_own()\n        print(f\"Your friends: {friendslist}\\n\")\n\n        # Get presence status (by list of XUID)\n        presence = await xbl_client.presence.get_presence_batch(\n            [\"2533274794093122\", \"2533274807551369\"]\n        )\n        print(f\"Statuses of some random players by XUID: {presence}\\n\")\n\n        # Get messages\n        messages = await xbl_client.message.get_inbox()\n        print(f\"Your messages: {messages}\\n\")\n\n        # Get profile by GT\n        profile = await xbl_client.profile.get_profile_by_gamertag(\"SomeGamertag\")\n        print(f\"Profile under SomeGamertag gamer tag: {profile}\\n\")\n\n\nasyncio.run(async_main())\n```\n\n## Contribute\n\n- Report bugs/suggest features\n- Add/update docs\n- Add additional xbox live endpoints\n\n## Credits\n\nThis package uses parts of [Cookiecutter](https://github.com/audreyr/cookiecutter)\nand the [audreyr/cookiecutter-pypackage](https://github.com/audreyr/cookiecutter-pypackage) project template.\nThe authentication code is based on [joealcorn/xbox](https://github.com/joealcorn/xbox)\n\nInformations on endpoints gathered from:\n\n- [XboxLive REST Reference](https://docs.microsoft.com/en-us/windows/uwp/xbox-live/xbox-live-rest/atoc-xboxlivews-reference)\n- [XboxLiveTraceAnalyzer APIMap](https://github.com/Microsoft/xbox-live-trace-analyzer/blob/master/Source/XboxLiveTraceAnalyzer.APIMap.csv)\n- [Xbox Live Service API](https://github.com/Microsoft/xbox-live-api)\n\n## Disclaimer\n\nXbox, 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.\n",
    "bugtrack_url": null,
    "license": "GPL",
    "summary": "A library to authenticate with Windows Live/Xbox Live and use their API",
    "version": "2.1.0",
    "project_urls": {
        "Homepage": "https://github.com/OpenXbox/xbox-webapi-python"
    },
    "split_keywords": [
        "xbox",
        "one",
        "live",
        "api"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "8ce09886eb787bcbdbadd059054460314c77d57ac78814ff98b24ad83e2e07db",
                "md5": "1dab116a130fc371b1b48f3ee53791c6",
                "sha256": "6df7aaa63f0a50dc64a40724c35a95e9b35b8af8f3994f07d4e83c00da83ca0b"
            },
            "downloads": -1,
            "filename": "xbox_webapi-2.1.0-py2.py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "1dab116a130fc371b1b48f3ee53791c6",
            "packagetype": "bdist_wheel",
            "python_version": "py2.py3",
            "requires_python": ">=3.8",
            "size": 60660,
            "upload_time": "2023-11-25T22:24:52",
            "upload_time_iso_8601": "2023-11-25T22:24:52.420439Z",
            "url": "https://files.pythonhosted.org/packages/8c/e0/9886eb787bcbdbadd059054460314c77d57ac78814ff98b24ad83e2e07db/xbox_webapi-2.1.0-py2.py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "f55a7af2bdd9725ebf905adb89fdcc78bfaae2e16ea7637db294febbbea443f6",
                "md5": "a0fe5a344e317055a8f48bef56012f7c",
                "sha256": "5fa3099b8597e7400583ca5b49a47d3548f74d74fb48fb5df4203734dea0fa16"
            },
            "downloads": -1,
            "filename": "xbox-webapi-2.1.0.tar.gz",
            "has_sig": false,
            "md5_digest": "a0fe5a344e317055a8f48bef56012f7c",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 303294,
            "upload_time": "2023-11-25T22:24:54",
            "upload_time_iso_8601": "2023-11-25T22:24:54.930807Z",
            "url": "https://files.pythonhosted.org/packages/f5/5a/7af2bdd9725ebf905adb89fdcc78bfaae2e16ea7637db294febbbea443f6/xbox-webapi-2.1.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-11-25 22:24:54",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "OpenXbox",
    "github_project": "xbox-webapi-python",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "xbox-webapi"
}
        
Elapsed time: 0.14486s